package TCP.echoserver2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {

    private ServerSocket serverSocket = null;
    ExecutorService pool = Executors.newCachedThreadPool();// 创建线程池


    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        while (true) {
            Socket socket = serverSocket.accept();

            pool.submit(new Runnable() {
                @Override
                public void run() {
                    processClient(socket);
                }
            });
        }
    }
    public void processClient(Socket socket){
        System.out.printf("[ip: %s port: %d]连接成功\n",socket.getInetAddress().toString(),socket.getPort());
        try(InputStream inputStream = socket.getInputStream()){
            try(OutputStream outputStream = socket.getOutputStream()){
                Scanner scanner = new Scanner(inputStream);
                while (true) {
                    if(!scanner.hasNext()){
                        System.out.printf("[ip: %s port: %d]断开连接\n",socket.getInetAddress().toString(),socket.getPort());
                        break;
                    }
                    String request = scanner.nextLine();
                    String response = process(request);


                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(response);
                    printWriter.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {

        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
